<template>
  <div
    :class="[
      'flex flex-col items-center w-full  relative ',
      isMobile() ? 'justify-start pt-10' : 'justify-center min-h-[30rem] h-full'
    ]"
  >
    <StudyTip />
    <div class="flex flex-wrap gap-2 justify-center items-center mt-10">
      <div
        class="relative"
        :style="{ 'min-width': item.length * 1.5 + 'rem' }"
        v-for="(item, index) in courseStore.words"
      >
        <div
          :class="[
            'h-[2rem] md:h-[4rem] text-primary rounded-[2px] border-b-2 border-solid text-[1.2em] md:text-[3.0em] leading-none transition-all  w-full',
            getWordsClassNames(index),
          ]"
        >
          <span v-if="inputValue" class="block w-full h-full text-center">{{
            userInputWords[index]?.userInput || ""
          }}</span>
        </div>
      </div>
      <input
        type="text"
        :value="inputValue"
        @input="handleInputChange"
        class="absolute opacity-0 w-full pl-5 bg-red-700 h-[5rem]"
        @focus="inputStatus = 'typing'"
        @blur="inputStatus = 'blur'"
        @keydown="handleKeydown"
        ref="wordInputRef"
      />
    </div>
  </div>

  <div class="flex gap-[3rem] items-center justify-center h-[5rem]">
    <StudyPlayKdd />
    <div
      class="tooltip tooltip-bottom"
      data-tip="答案  快捷键 ctrl 2"
      @click="autoTip()"
    >
      <button class="btn btn-sm btn-dash">
        <template v-if="!isMobile()">
        <kbd class="kbd kbd-xs">ctrl</kbd> <kbd class="kbd kbd-xs">2</kbd> 
        </template>
        答案
      </button>
    </div>
    <div
      class="tooltip"
      data-tip="提交 快捷键 enter"
      @click="clickSubmitAnswer()"
    >
      <button class="btn btn-sm btn-dash btn-primary">
        <template v-if="!isMobile()">
          <kbd class="kbd kbd-xs">enter</kbd>
        </template>
        提交
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from "vue";
import { usePlayTipSound } from "@/composables/study/useSound";
import { useInput } from "~/composables/study/input";
import { isMobile } from "~/composables/common/mobile";
import {
  useTip,
  useInput as useInputStatus,
} from "~/composables/study/studentStatus";
import { useCourseStore } from "~/stores/course";
import { useStudyInput } from "~/composables/study/useStudy";
import {
  registerShortcut,
  cancelShortcut,
} from "~/composables/user/globalShortcut";
import type { Shortcut } from "~/composables/user/globalShortcut";
const { goNext, AnswerErr, AnswerRight } = useStudyInput();
// 初始化音效
const { playTypingSound } = usePlayTipSound();
const {  autoTip } = useTip();
const inputStatus = ref<"typing" | "blur">("typing");
const courseStore = useCourseStore();
console.log(courseStore.words);
// 单词相关数据处理
const wordInputRef = ref<HTMLInputElement | null>(null);
const progress = ref(10);
function getWordsClassNames(index: number) {
  const word = findWordById(index)!;
  if (word.incorrect && inputStatus.value === "typing") {
    return `text-red-500 border-b-red-500`;
  }
  if (word.isActive && inputStatus.value === "typing") {
    return "text-primary border-b-primary";
  }
  if (!findModeInput() && !word.incorrect) {
    return "text-green-500 border-b-green-500";
  }
  if (userInputIsEnd.value && !word.incorrect) {
    return "text-green-500 border-b-green-500";
  }
  return "border-b-gray-300";
}
function clickSubmitAnswer() {
  submitAnswer(AnswerRight, AnswerErr);
}
// 处理键盘事件
const handleKeydown = (event: KeyboardEvent) => {
  if (
    event.code === "Backspace" &&
    event.ctrlKey &&
    navigator.userAgent.includes("Windows")
  ) {
    event.preventDefault();
    return;
  }
  if (event.ctrlKey) {
    event.preventDefault();
    return;
  }
  if (userInputIsEnd.value) {
    goNext();
    event.preventDefault();
    return;
  }
  handleKeyboardInput(event, {
    useSpaceSubmitAnswer: {
      enable: true,
      rightCallback: () => {
        AnswerRight();
      },
      errorCallback: () => {
        AnswerErr();
      },
    },
  });
};

// 处理输入变化
const handleInputChange = (e: Event) => {
  const target = e.target as HTMLInputElement;
  setInputValue(target.value);
};
const registeredShortcuts: Shortcut[] = [];
// 组件挂载时初始化
onMounted(() => {
  wordInputRef.value?.focus();
  // 初始化输入系统
  registeredShortcuts.push(
    registerShortcut(
      "ctrl+2",
      (e) => {
        e.preventDefault();
        autoTip();
      },
      { priority: "high" }
    )
  );
  registeredShortcuts.push(
    registerShortcut(
      "enter",
      (e) => {
        e.preventDefault();
        clickSubmitAnswer();
      },
      { priority: "high" }
    )
  );
});

// 组件卸载时取消注册的快捷键
onUnmounted(() => {
  registeredShortcuts.forEach((shortcut) => {
    cancelShortcut(shortcut);
  });
});

const {
  initialize,
  handleKeyboardInput,
  submitAnswer,
  setInputValue,
  findModeInput,
  findWordById,
  userInputIsEnd,
  inputValue,
  userInputWords,
} = useInput({
  source: () => courseStore.currentData?.english || "",
  setInputCursorPosition: (position: number) => {
    nextTick(() => {
      if (wordInputRef.value) {
        wordInputRef.value.setSelectionRange(position, position);
        wordInputRef.value.focus();
      }
    });
  },
  getInputCursorPosition: () => wordInputRef.value?.selectionStart || 0,
  inputChangedCallback: () => {
    playTypingSound();
  },
});
watch(() => courseStore.words, initialize, { immediate: true });
</script>
